package com.boarsoft.message;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.Util;
import com.boarsoft.common.util.InetUtil;
import com.boarsoft.common.util.StreamUtil;

public class MessageConfig {
	private static Logger log = LoggerFactory.getLogger(MessageConfig.class);
	private static Properties prop = new Properties();
	//
	// 外置的队列配置文件目录：mq.conf.dir
	public static String CONF_DIR = "./";
	private static String CONF_FILE_PATH;
	public static String APP_ROOT = "";

	private static InetAddress address = InetUtil.getAddress();
	private static String ip = InetUtil.getIp();
	private static int port = Math.max(9908, InetUtil.getPort());
	private static String addr = InetUtil.getAddr();
	private static String hostName = InetUtil.getHostName();

	static {
		init();
	}

	public static void init() {
		String path = getString("message.conf.dir", "conf/");
		InputStream is = MessageConfig.class.getClassLoader()//
				.getResourceAsStream(path.concat("config.properties"));
		try {
			if (is == null) {
				log.warn("Can not found classpath:{}/config.properties", path);
			} else {
				prop.load(is);
			}

			APP_ROOT = getString("app.root", APP_ROOT);
			CONF_DIR = getString("mq.conf.dir", CONF_DIR);
			// 检查并读取外围的配置文件，有则覆盖现有配置文件
			CONF_FILE_PATH = CONF_DIR.concat("/config.properties");
			File cf = new File(CONF_FILE_PATH);
			if (cf.exists()) {
				log.info("Read external config file {}", CONF_FILE_PATH);
				prop.load(new BufferedInputStream(new FileInputStream(cf)));
			}

			address = InetUtil.getLocalAddress(//
					getString("message.ens", getString("my.ens")), //
					getString("message.host", getString("my.host")));
			ip = address.getHostAddress();
			hostName = address.getHostName();
			port = Util.str2int(getString("message.port", getString("my.port")), port);
			addr = new StringBuilder(ip).append(":").append(port).toString();
		} catch (IOException e) {
			log.error("Error on load message config.", e);
			throw new RuntimeException(e);
		} finally {
			StreamUtil.close(is);
		}
	}

	public static int getInt(String key, int value) {
		String s = getString(key, String.valueOf(value));
		return Util.str2int(s, value);
	}

	/**
	 * 系统变量优先，取不到再取配置文件中的变量
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static String getString(String key, String value) {
		return System.getProperty(key, prop.getProperty(key, value));
	}

	public static String getString(String key) {
		return System.getProperty(key, prop.getProperty(key, null));
	}

	public static void flush() throws FileNotFoundException, IOException, URISyntaxException {
		URL url = MessageConfig.class.getClassLoader().getResource(CONF_FILE_PATH);
		log.warn("Overwrite MessageConfig/{} now", CONF_FILE_PATH);
		prop.store(new FileOutputStream(new File(url.toURI())), Util.getStdmfDateTime());
	}

	public static String getIp() {
		return ip;
	}

	public static int getPort() {
		return port;
	}

	public static String getHostName() {
		return hostName;
	}

	public static String getAddr() {
		return addr;
	}

	public static InetAddress getAddress() {
		return address;
	}

	public static void set(String k, String v) {
		prop.setProperty(k, v);
	}

	public static String get(String k) {
		return prop.getProperty(k);
	}

}